package yxy.apple.http.request;

import java.util.HashMap;

import yxy.apple.http.HTTPException;
import yxy.apple.util.URLUtility;
import yxy.apple.util.http.HTTPProtocol;

public class FormRequest extends PostRequest<HashMap<String, String>> {

	private String encoding = "UTF-8";

	public FormRequest(String url) {
		super(url);
		this.setBody(new HashMap<String, String>());
		this.setHeader(HTTPProtocol.HeaderKey.ContentType, HTTPProtocol.MimeType.UTF8URLEncodedForm);
	}

	public FormRequest(String url, String encoding) {
		super(url);
		this.encoding = encoding;
		this.setHeader(HTTPProtocol.HeaderKey.ContentType,
				HTTPProtocol.MimeType.URLEncodedForm + "; charset=" + encoding);
	}

	@Override
	@Deprecated
	public void setBody(HashMap<String, String> form) {
		super.setBody(form);
	}

	public void setFormField(String field, String value) {
		this.body().put(field, value);
	}

	@Override
	protected String bodyToString(HashMap<String, String> body) {
		return URLUtility.toQueryString(body, true);
	}

	@Override
	public byte[] encodedBody() throws HTTPException {
		try {
			String string = this.bodyToString(this.body());
			if (string != null) {
				return string.getBytes(this.encoding);
			} else {
				return null;
			}
		} catch (Exception e) {
			throw new HTTPException(e);
		}
	}
}
